package dao.imp;

import dao.PhoneAddressDao;
import domain.PhoneAddress;
import utils.JDBCutils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class PhoneAddressDaoimp implements PhoneAddressDao {
    @Override
    public boolean addPhone(PhoneAddress p) {
        String sql="insert into xscj(name,phonenum,position,company) values(?,?,?,?) " ;
        String[] str={p.getName(), p.getPhonenum(),p.getPosition(),p.getCompany()};
        int result= JDBCutils.eu(sql,str);
        if(result==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean deletePhone(String name) {
        String sql="delete from xscj where name=?" ;
        String[] str={name};
        int result= JDBCutils.eu(sql,str);
        if(result==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean updatePhone(PhoneAddress p) {
        String sql="update xscj set name=? ,phonenum=?,position=?,company=? where id=? " ;
        Object[] str={p.getName(),p.getPhonenum(),p.getPosition(),p.getCompany(),p.getId()};
        int result= JDBCutils.eu(sql,str);
        if(result==1){
            return true;
        }
        return false;
    }

    @Override
    public ArrayList<PhoneAddress> selectAll() {
        ArrayList<PhoneAddress> arr=new ArrayList<>();
        String sql="select * from xscj";
        ResultSet rs=JDBCutils.eq(sql);
        try{
            while(rs.next()){
                arr.add(new PhoneAddress(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return arr;
    }

    @Override
    public PhoneAddress selectOnename(String name) {
        PhoneAddress p=new PhoneAddress();
        String sql="select * from xscj where name=?";
        ResultSet rs=JDBCutils.eqo(sql,name);
        try{
            if(rs.next()){
                p=new PhoneAddress(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return p;
    }
}
